package com.listeningframework.boot.autoconfigure.mail.senders;

import com.listeningframework.boot.autoconfigure.mail.domains.ListeningMailMessage;
import com.listeningframework.boot.autoconfigure.mail.domains.ListeningMailProperties;
import com.listeningframework.boot.constants.MailHosts;
import com.listeningframework.boot.exception.BusinessException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;

/**
 * Listening Mail Sender
 *
 * @author lixining
 * @version $Id: ListeningCustomMailSender.java, v 0.1 2015年11月4日 上午11:14:10 lixining Exp $
 */
public class ListeningCustomMailSender extends ListeningBaseMailSender {

    /**
     * Send Smart Simple Message
     *
     * @param properties 邮件账号配置
     * @param message    邮件内容
     * @throws BusinessException 简单邮件发送异常
     */
    public void sendSimpleMessage(ListeningMailProperties properties, ListeningMailMessage message) throws BusinessException {
        JavaMailSender mailsender = getCustomMailSender(properties);
        message.setSendFrom(properties.getUsername());
        mailsender.send(getSimpleMailMessage(message));
    }

    /**
     * Send Smart Mime Message
     *
     * @param properties 邮件账号配置
     * @param message    邮件内容
     * @throws BusinessException 发送异常
     */
    public void sendMimeMessage(ListeningMailProperties properties, ListeningMailMessage message) throws BusinessException {
        JavaMailSender mailsender = getCustomMailSender(properties);
        message.setSendFrom(properties.getUsername());
        mailsender.send(getMimeMailMessage(mailsender, message));
    }

    /**
     * Custom Mail Sender
     *
     * @param properties 邮件账号配置
     * @return JavaMailSender
     * @throws BusinessException 构建Sender异常
     */
    private JavaMailSender getCustomMailSender(ListeningMailProperties properties) throws BusinessException {
        try {
            JavaMailSenderImpl customMailSender = new JavaMailSenderImpl();
            MailHosts mailHost = properties.getMailHost();
            if (mailHost == null) {
                throw new BusinessException("mail host cant be null");
            }
            customMailSender.setHost(mailHost.getCode());
            customMailSender.setUsername(properties.getUsername());
            customMailSender.setPassword(properties.getPassword());
            Properties prop = new Properties();
            prop.put("mail.smtp.auth", "true");
            prop.put("mail.smtp.timeout", "25000");
            customMailSender.setJavaMailProperties(prop);
            return customMailSender;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new BusinessException("generate custom mailsender fail", e);
        }
    }
}
